#ifndef LHC_FILE_STREAM_INCLUDED_H_
#define LHC_FILE_STREAM_INCLUDED_H_

#include "IStream.h"
#include "UnicodeString.h"
#include "Macros.h"
#include <boost/noncopyable.hpp>

#ifdef _WIN32
#include <Windows.h>
#endif

namespace lhcutils
{

struct FileOpenMode
{
	enum Value
	{
		// Create a new file. Throw an exception if the file already exists.
		CreateNew,
		
		// Create a new file if it does not exist. If it does exist, truncate the existing file.
		CreateOrTruncate,
		
		// Open an existing file. If the file does not exist, throw an exception.
		OpenExisting,
		
		// Open an existing file or create it if it does not exist.
		OpenOrCreate,

		// Truncates an existing file. Throw an exception if it does not exist.
		Truncate,
		
		// Appends to the end of an existing file or creates a new file.
		// On some platforms you may not be able to do anything other than append data (ie no seeking backward or reading).
		AppendOrCreate
	};
};

namespace FileAccess
{
	const int Read = 1;
	const int Write = 2;
	const int ReadWrite = 3;
}

class FileStream : public IStream, private boost::noncopyable
{
public:
	// Throws: FileNotFoundException, IoException
	FileStream(const UnicodeString& filePath, FileOpenMode::Value mode, int fileAccess);

#ifdef _WIN32
	// Takes ownership of the handle
	explicit FileStream(HANDLE handle, int fileAccess);
#endif

	virtual bool CanRead() OVERRIDE;
	virtual bool CanWrite() OVERRIDE;
	virtual bool CanSeek() OVERRIDE;

	virtual boost::int64_t GetPosition() OVERRIDE;
	virtual void SetPosition(boost::int64_t newPosition, SeekOrigin::Value origin) OVERRIDE;
	virtual void Flush() OVERRIDE;
	virtual size_t Read(void* buffer, size_t count) OVERRIDE;
	virtual void Write(const void* buffer, size_t count) OVERRIDE;

#ifdef _WIN32
	HANDLE GetWin32Handle();
#endif

	virtual void Close() OVERRIDE;
	virtual ~FileStream();

private:
#ifdef _WIN32
	HANDLE m_handle;
	DWORD m_fileType;
	int m_fileAccess;

	DWORD FileAccessAsDword(int fileAccess);
	DWORD ModeAsDword(FileOpenMode::Value mode);
	DWORD SeekOriginAsDword(SeekOrigin::Value origin);
#endif
};

}

#endif

/*
 Copyright 2011 Greg Najda

   Licensed under the Apache License, Version 2.0 (the "License");
   you may not use this file except in compliance with the License.
   You may obtain a copy of the License at

       http://www.apache.org/licenses/LICENSE-2.0

   Unless required by applicable law or agreed to in writing, software
   distributed under the License is distributed on an "AS IS" BASIS,
   WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
   See the License for the specific language governing permissions and
   limitations under the License.
*/
